import React, { useState, useEffect } from 'react';
import { Button, Input, Pagination, Popconfirm, message, Empty } from 'antd';
import { DeleteOutlined } from '@ant-design/icons';
import { addComment, deleteComment, listCommentPage } from '../../api/commentController';
import { addCommentReply, deleteCommentReply } from '../../api/commentReplyController';

const { TextArea } = Input;

interface UserInfo {
    id: string;
    nickName: string;
    avatarUrl: string;
    // ... other user fields
}

interface BaseComment {
    id: string;
    content: string;
    userInfo: UserInfo;
}

interface CommentReply extends BaseComment {
    commentid: string;
    replytime: string;
    replyUserInfo: UserInfo;
}

interface CommentType extends BaseComment {
    targetid: string;
    targettype: number;
    commenttime: string;
    commentReplies: CommentReply[];
}

interface CommentsProps {
    targetId: string | number;
    targetType: number; // 0 for books, 1 for posts
    currentUserId: string; // 当前登录用户的ID
    defaultAvatar?: string; // 添加默认头像属性
}

// 创建一个独立的头像组件
const UserAvatar = React.memo(({ userInfo, defaultAvatar }: { userInfo: UserInfo, defaultAvatar: string }) => {
    return (
        <img 
            src={userInfo.avatarUrl || defaultAvatar}
            alt={userInfo.nickName}
            className="w-full h-full rounded-full object-cover"
            onError={(e) => {
                const target = e.target as HTMLImageElement;
                target.onerror = null;
                target.src = defaultAvatar;
            }}
            loading="lazy"
        />
    );
});

// 使用 React.memo 包装 CommentItem 组件
const CommentItem = React.memo(({ 
    comment, 
    isReply = false,
    onReply,
    onDelete,
    onDeleteReply,
    showReplyInput,
    replyText,
    currentUserId,
    defaultAvatar,
    handleReplyTextChange,
    toggleReplyInput,
    handleReply
}: {
    comment: CommentType | CommentReply;
    isReply?: boolean;
    onReply: (id: string) => void;
    onDelete: (id: string) => void;
    onDeleteReply: (id: string) => void;
    showReplyInput: { [key: string]: boolean };
    replyText: { [key: string]: string };
    currentUserId: string;
    defaultAvatar: string;
    handleReplyTextChange: (commentId: string, value: string) => void;
    toggleReplyInput: (commentId: string) => void;
    handleReply: (commentId: string) => void;
}) => {
    const time = isReply 
        ? (comment as CommentReply).replytime 
        : (comment as CommentType).commenttime;

    // 获取被回复用户的信息
    const replyToUser = isReply ? (comment as CommentReply).replyUserInfo : null;

    return (
        <div className={`flex gap-3 ${!isReply ? 'mb-6' : 'mt-3 ml-10'}`}>
            <div className={isReply ? 'flex-shrink-0 w-8 h-8' : 'flex-shrink-0 w-10 h-10'}>
                <UserAvatar userInfo={comment.userInfo} defaultAvatar={defaultAvatar} />
            </div>
            <div className="flex-1">
                <div className="flex items-center justify-between">
                    <div className="flex items-center gap-2">
                        <span className={`font-medium ${isReply ? 'text-sm' : 'text-base'}`}>
                            {comment.userInfo.nickName}
                        </span>
                        {isReply && replyToUser && (
                            <>
                                <span className="text-gray-400 text-sm">回复</span>
                                <span className="font-medium text-sm">{replyToUser.nickName}</span>
                            </>
                        )}
                    </div>
                    <span className={`text-gray-400 ${isReply ? 'text-xs' : 'text-sm'}`}>
                        {time}
                    </span>
                </div>
                <p className={`my-1.5 ${isReply ? 'text-sm text-gray-600' : 'text-base text-gray-700'}`}>
                    {comment.content}
                </p>
                <div className="flex gap-4">
                    {!isReply && (
                        <button 
                            className="text-blue-500 text-sm hover:text-blue-700 transition-colors"
                            onClick={() => toggleReplyInput(comment.id)}
                        >
                            回复
                        </button>
                    )}
                    {comment.userInfo.id === currentUserId && (
                        <Popconfirm
                            title="确定要删除这条评论吗？"
                            onConfirm={() => isReply ? 
                                onDeleteReply(comment.id) : 
                                onDelete(comment.id)
                            }
                            okText="确定"
                            cancelText="取消"
                        >
                            <button className="text-red-400 text-sm hover:text-red-600 transition-colors">
                                <DeleteOutlined /> 删除
                            </button>
                        </Popconfirm>
                    )}
                </div>
                
                {/* 回复输入框部分 */}
                {!isReply && showReplyInput[comment.id] && (
                    <div className="mt-2 bg-gray-50 p-3 rounded-lg">
                        <Input.TextArea
                            value={replyText[comment.id] || ''}
                            onChange={e => handleReplyTextChange(comment.id, e.target.value)}
                            placeholder={`回复 ${comment.userInfo.nickName}...`}
                            rows={2}
                            className="mb-2 text-sm"
                            autoFocus
                        />
                        <div className="flex justify-end gap-2">
                            <Button 
                                size="small" 
                                onClick={() => toggleReplyInput(comment.id)}
                                className="text-sm"
                            >
                                取消
                            </Button>
                            <Button 
                                type="primary" 
                                size="small"
                                onClick={() => handleReply(comment.id)}
                                className="text-sm"
                            >
                                回复
                            </Button>
                        </div>
                    </div>
                )}
                
                {/* 回复列表部分 */}
                <div className="space-y-3">
                    {!isReply && (comment as CommentType).commentReplies?.map(reply => (
                        <CommentItem 
                            key={reply.id} 
                            comment={reply} 
                            isReply 
                            onReply={onReply}
                            onDelete={onDelete}
                            onDeleteReply={onDeleteReply}
                            showReplyInput={showReplyInput}
                            replyText={replyText}
                            currentUserId={currentUserId}
                            defaultAvatar={defaultAvatar}
                            handleReplyTextChange={handleReplyTextChange}
                            toggleReplyInput={toggleReplyInput}
                            handleReply={handleReply}
                        />
                    ))}
                </div>
            </div>
        </div>
    );
});

export default function Comments({ targetId, targetType, currentUserId, defaultAvatar = 'https://api.dicebear.com/7.x/miniavs/svg?seed=1' }: CommentsProps) {
    const [commentText, setCommentText] = useState('');
    const [replyText, setReplyText] = useState<{ [key: string]: string }>({});
    const [showReplyInput, setShowReplyInput] = useState<{ [key: string]: boolean }>({});
    const [currentPage, setCurrentPage] = useState(1);
    const [total, setTotal] = useState(0);
    const [comments, setComments] = useState<CommentType[]>([]);
    const pageSize = 10;

    // 获取评论列表
    const fetchComments = async () => {
        try {
            const response = await listCommentPage({
                current: currentPage,
                pageSize: pageSize,
                targetId: Number(targetId),
                targetType
            });
            if (response.code === 200) {
                setComments(response.data.records);
                setTotal(parseInt(response.data.total));
            }
        } catch (error) {
            message.error('获取评论失败');
        }
    };

    useEffect(() => {
        if (targetId) {
            fetchComments();
        }
    }, [targetId, currentPage]);

    const handleComment = async () => {
        if (!commentText.trim()) {
            message.warning('评论内容不能为空');
            return;
        }
        try {
            const response = await addComment({
                targetId: Number(targetId),
                targetType,
                content: commentText.trim()
            });
            if (response.code === 200) {
                message.success('评论成功');
                setCommentText('');
                fetchComments();
            }
        } catch (error) {
            message.error('评论失败');
        }
    };

    const handleReply = async (commentId: string) => {
        if (!replyText[commentId]?.trim()) {
            message.warning('回复内容不能为空');
            return;
        }

        // 找到对应的主评论
        const parentComment = comments.find(c => c.id === commentId);
        if (!parentComment) {
            message.error('评论不存在');
            return;
        }

        try {
            const response = await addCommentReply({
                commentId: Number(commentId),
                content: replyText[commentId].trim(),
                replyUserId: parentComment.userInfo.id 
            });
            if (response.code === 200) {
                message.success('回复成功');
                setReplyText(prev => ({ ...prev, [commentId]: '' }));
                setShowReplyInput(prev => ({ ...prev, [commentId]: false }));
                fetchComments();
            } else {
                message.error(response.message);
                // 在失败时也关闭输入框并清空内容
                setReplyText(prev => ({ ...prev, [commentId]: '' }));
                setShowReplyInput(prev => ({ ...prev, [commentId]: false }));
            }
        } catch (error) {
            message.error('回复失败');
            // 在错误时也关闭输入框并清空内容
            setReplyText(prev => ({ ...prev, [commentId]: '' }));
            setShowReplyInput(prev => ({ ...prev, [commentId]: false }));
        }
    };

    const handleDelete = async (commentId: string) => {
        try {
            // 先删除所有相关的回复
            const comment = comments.find(c => c.id === commentId);
            if (comment && comment.commentReplies?.length > 0) {
                // 使用 Promise.all 并行删除所有回复
                await Promise.all(
                    comment.commentReplies.map(reply => 
                        deleteCommentReply({
                            id: Number(reply.id)
                        })
                    )
                );
            }

            // 然后删除主评论
            const response = await deleteComment({
                id: Number(commentId)
            });
            
            if (response.code === 200) {
                setComments(prevComments => 
                    prevComments.filter(comment => comment.id !== commentId)
                );
                setTotal(prev => Math.max(0, prev - 1));
                message.success('删除成功');
                fetchComments(); // 刷新评论列表以确保数据同步
            }
        } catch (error) {
            message.error('删除失败');
            console.error('删除评论失败:', error);
        }
    };

    const handleDeleteReply = async (replyId: string) => {
        try {
            const response = await deleteCommentReply({
                id: Number(replyId)
            });
            if (response.code === 200) {
                setComments(prevComments => 
                    prevComments.map(comment => ({
                        ...comment,
                        commentReplies: comment.commentReplies?.filter(reply => reply.id !== replyId) || []
                    }))
                );
                message.success('删除回复成功');
            }
        } catch (error) {
            message.error('删除回复失败');
        }
    };

    const toggleReplyInput = (commentId: string) => {
        setShowReplyInput(prev => ({
            ...prev,
            [commentId]: !prev[commentId]
        }));
        // 如果是关闭输入框，清空输入内容
        if (showReplyInput[commentId]) {
            setReplyText(prev => ({
                ...prev,
                [commentId]: ''
            }));
        }
    };

    const handleReplyTextChange = (commentId: string, value: string) => {
        setReplyText(prev => ({
            ...prev,
            [commentId]: value
        }));
    };

    return (
        <div className="bg-white rounded-lg p-6 mt-6">
            <div className="flex items-center justify-between mb-6">
                <h2 className="text-xl font-bold">评论 ({total})</h2>
            </div>

            {/* 评论输入框 */}
            <div className="mb-6">
                <TextArea
                    value={commentText}
                    onChange={e => setCommentText(e.target.value)}
                    placeholder="写下你的评论..."
                    rows={4}
                    className="mb-4"
                />
                <div className="flex justify-end gap-4">
                    <Button onClick={() => setCommentText('')}>重置</Button>
                    <Button type="primary" onClick={handleComment}>发布评论</Button>
                </div>
            </div>

            {/* 评论列表 - 添加空状态展示 */}
            <div className="space-y-6">
                {comments.length > 0 ? (
                    comments.map(comment => (
                        <CommentItem 
                            key={comment.id} 
                            comment={comment}
                            onReply={handleReply}
                            onDelete={handleDelete}
                            onDeleteReply={handleDeleteReply}
                            showReplyInput={showReplyInput}
                            replyText={replyText}
                            currentUserId={currentUserId}
                            defaultAvatar={defaultAvatar}
                            handleReplyTextChange={handleReplyTextChange}
                            toggleReplyInput={toggleReplyInput}
                            handleReply={handleReply}
                        />
                    ))
                ) : (
                    <Empty
                        image={Empty.PRESENTED_IMAGE_SIMPLE}
                        description={
                            <span className="text-gray-500">
                                暂无评论，快来发表第一条评论吧！
                            </span>
                        }
                    />
                )}
            </div>

            {/* 只在有评论时显示分页 */}
            {total > 0 && (
                <div className="mt-6 flex justify-center">
                    <Pagination
                        current={currentPage}
                        total={total}
                        pageSize={pageSize}
                        onChange={setCurrentPage}
                        showSizeChanger={false}
                    />
                </div>
            )}
        </div>
    );
} 